package com.qikux.utils;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.MathGenerator;

import java.lang.reflect.Method;
import java.util.Random;

/**
 * 验证码工具类
 */
public class CodeUtils {

    /**
     * 生成验证码
     * @return
     */
    public static AbstractCaptcha createCaptcha(int width, int height) throws Exception{
        // 将生成验证码的方法名写入到 数组中
        String[] methods = {"createLineCaptcha",  "createCircleCaptcha", "createShearCaptcha"} ;

        // 使用 随机数 随机返回一个方法名
        int index = new Random().nextInt(methods.length) ;

        String methodName = methods[index] ;

        // 通过 反射获取 CaptchaUtil的 [methodName] 方法
        Class<CaptchaUtil> captchaUtilClass = CaptchaUtil.class;

        Method method = captchaUtilClass.getMethod(methodName, new Class[]{int.class, int.class, int.class, int.class});

        // 通过反射调用 method 方法
        AbstractCaptcha captcha = (AbstractCaptcha)method.invoke(null, width, height, 4, 4);
        if(Math.random() < 0.5) {
            // 设置四则运算
            captcha.setGenerator(new MathGenerator());
            captcha.createCode();
        }

        return captcha ;

    }

    public static void main(String[] args) throws Exception{

        AbstractCaptcha captcha = createCaptcha(140, 40);

        System.out.println(captcha.getCode());

        boolean verify = captcha.verify(captcha.getCode());

        System.out.println(verify);

    }

}
